package com.book.service.impl;

import com.book.service.LuaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @author SuperYu  2024/8/14
 */
@Service
public class LuaServiceImpl implements LuaService {

    // @Resource
    // DefaultRedisScript<Long> defaultRedisScript;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public long executeLua() {

        String script = "local key = KEYS[1]\n" +
                "local val = tonumber(redis.call('get', key));\n" +
                "if val > 0 then\n" +
                "    local num = tonumber(redis.call('decr', key ))\n" +
                "    return num;\n" +
                "else\n" +
                "    return 0\n" +
                "end" ;


        ArrayList<String> keys = new ArrayList();
        keys.add("goods");


        Long result = stringRedisTemplate.opsForValue()
                .getOperations()
                .execute(new DefaultRedisScript<>(script, Long.class), keys);

        return result;
    }
}
